<template>
	<div class="medical-report-container">
		<!-- 患者搜索卡片 -->
		<el-card class="search-card" shadow="never">
			<template #header>
				<div class="card-header">
					<span class="header-title">患者搜索</span>
					<el-tag type="info" size="small">按诊疗号搜索</el-tag>
				</div>
			</template>
			
			<el-row :gutter="20" align="middle">
				<el-col :span="18">
					<el-input 
						v-model="visitId" 
						placeholder="请输入患者诊疗号" 
						clearable 
						size="large"
						class="search-input"
						@keyup.enter="getPatientByvisitId"
					>
						<template #prefix>
							<i class="el-icon-search"></i>
						</template>
					</el-input>
				</el-col>
				<el-col :span="6">
					<el-button 
						type="primary" 
						@click="getPatientByvisitId" 
						size="large"
						class="search-btn"
					>
						搜索患者
					</el-button>
				</el-col>
			</el-row>
		</el-card>

		<!-- 患者选择卡片 -->
		<el-card 
			v-if="patientList.length > 0" 
			class="patient-card" 
			shadow="never"
		>
			<template #header>
				<div class="card-header">
					<span class="header-title">选择患者</span>
					<span class="patient-count">{{ patientList.length }} 位患者</span>
				</div>
			</template>
			
			<el-radio-group v-model="selectedPatient" class="patient-list">
				<el-card 
					v-for="patient in patientList" 
					:key="patient.visitId"
					shadow="hover"
					:class="['patient-item', { 'selected': selectedPatient?.visitId === patient.visitId }]"
				>
					<el-radio :label="patient" class="patient-radio">
						<div class="patient-info">
							<el-avatar 
								size="medium" 
								:style="{ backgroundColor: stringToColor(patient.patientName) }"
								class="patient-avatar"
							>
								{{ getInitials(patient.patientName) }}
							</el-avatar>
							<div class="patient-details">
								<div class="patient-name">{{ patient.patientName }}</div>
								<div class="patient-id">
									<el-tag size="small" type="info" round>
										<i class="el-icon-user"></i>
										诊疗号：{{ patient.visitId }}
									</el-tag>
								</div>
							</div>
						</div>
					</el-radio>
				</el-card>
			</el-radio-group>
		</el-card>

		<!-- 病历表单卡片 -->
		<el-card 
			v-if="selectedPatient" 
			class="form-card" 
			shadow="never"
		>
			<template #header>
				<div class="card-header">
					<div class="header-left">
						<i class="el-icon-document form-icon"></i>
						<span class="header-title">新建病历报告</span>
					</div>
					<el-tag type="success" size="small">
						当前患者：{{ selectedPatient.patientName }}
					</el-tag>
				</div>
			</template>

			<el-form 
				:model="resultData" 
				ref="formRef" 
				label-width="120px"
				class="medical-form"
			>
				<el-row :gutter="40">
					<!-- 左侧表单 -->
					<el-col :span="12">
						<!-- 报告类型 -->
						<el-form-item label="报告类型" prop="reportType">
							<el-select 
								v-model="resultData.reportType" 
								placeholder="请选择报告类型"
								size="large"
								class="full-width"
							>
								<el-option label="检验" value="检验">
									<div class="option-item">
										<i class="el-icon-document type-icon test"></i>
										<span>检验</span>
									</div>
								</el-option>
								<el-option label="影像" value="影像">
									<div class="option-item">
										<i class="el-icon-picture type-icon image"></i>
										<span>影像</span>
									</div>
								</el-option>
								<el-option label="病理" value="病理">
									<div class="option-item">
										<i class="el-icon-video-camera type-icon pathology"></i>
										<span>病理</span>
									</div>
								</el-option>
							</el-select>
						</el-form-item>

						<!-- 报告名称 -->
						<el-form-item label="报告名称" prop="reportName">
							<el-select 
								v-model="selectedItem" 
								placeholder="请选择或搜索报告名称"
								filterable 
								size="large"
								@change="handleItemChange"
								class="full-width"
							>
								<el-option 
									v-for="item in itemList" 
									:key="item.itemCode"
									:label="item.itemName"
									:value="item.itemCode"
								>
									<div class="option-item">
										<span class="item-name">{{ item.itemName }}</span>
										<span class="item-code">{{ item.itemCode }}</span>
									</div>
								</el-option>
							</el-select>
							
							<div v-if="resultData.itemCode" class="item-code-display">
								<el-tag size="small">
									<i class="el-icon-price-tag"></i>
									报告编号：{{ resultData.itemCode }}
								</el-tag>
							</div>
						</el-form-item>

						<!-- 结论 -->
						<el-form-item label="结论" prop="conclusion">
							<el-input 
								v-model="resultData.conclusion" 
								type="textarea" 
								:rows="4"
								placeholder="请输入诊断结论"
								resize="none"
								show-word-limit
								maxlength="500"
								class="full-width"
							/>
						</el-form-item>
					</el-col>

					<!-- 右侧表单 -->
					<el-col :span="12">
						<!-- 文件上传 -->
						<el-form-item label="影像文件">
							<el-upload
								class="file-upload"
								drag
								:auto-upload="false"
								:show-file-list="false"
								:on-change="handleFileChange"
								:before-remove="removeFile"
								accept="image/*,application/pdf"
							>
								<i class="el-icon-upload"></i>
								<div class="el-upload__text">
									将文件拖到此处，或<em>点击上传</em>
								</div>
								<template #tip>
									<div class="el-upload__tip">
										支持 JPG、PNG、GIF、PDF 格式，大小不超过 50MB
									</div>
								</template>
							</el-upload>
							
							<div v-if="selectedFile" class="file-preview">
								<el-card shadow="never" class="file-card">
									<div class="file-info">
										<i class="el-icon-picture file-icon" :style="{ color: getFileIconColor(selectedFile) }"></i>
										<div class="file-details">
											<div class="file-name">{{ selectedFile.name }}</div>
											<div class="file-size">{{ formatFileSize(selectedFile.size) }}</div>
										</div>
										<el-button 
											type="danger" 
											circle 
											size="small"
											@click="removeFile"
											class="remove-btn"
										>
											<i class="el-icon-close"></i>
										</el-button>
									</div>
								</el-card>
							</div>
						</el-form-item>
					</el-col>
				</el-row>

				<!-- 结构化结果 - 全宽 -->
				<div class="structured-result-section">
					<div class="section-header">
						<i class="el-icon-s-data"></i>
						<span>结构化结果</span>
					</div>
					
					<el-row :gutter="20" class="result-fields">
						<el-col :span="8">
							<el-form-item label="检查部位">
								<el-input 
									v-model="checkSite" 
									type="textarea" 
									:rows="3"
									placeholder="如：胸部"
									resize="none"
								/>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item label="表现">
								<el-input 
									v-model="performance" 
									type="textarea" 
									:rows="3"
									placeholder="如：右肺下叶可见斑片状高密度影"
									resize="none"
								/>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item label="印象">
								<el-input 
									v-model="impression" 
									type="textarea" 
									:rows="3"
									placeholder="如：右肺下叶炎症"
									resize="none"
								/>
							</el-form-item>
						</el-col>
					</el-row>
					
					<!-- JSON预览 -->
					<el-card class="json-preview-card" shadow="never">
						<template #header>
							<div class="preview-header">
								<i class="el-icon-view"></i>
								<span>JSON预览</span>
								<el-tooltip content="结构化结果将自动转换为JSON格式" placement="top">
									<i class="el-icon-info"></i>
								</el-tooltip>
							</div>
						</template>
						<pre class="json-preview">{{ resultItemsJson }}</pre>
					</el-card>
				</div>

				<!-- 表单操作按钮 -->
				<div class="form-actions">
					<el-button 
						type="primary" 
						@click="submitForm" 
						:loading="submitting"
						size="large"
						class="submit-btn"
					>
						<i v-if="!submitting" class="el-icon-check"></i>
						{{ submitting ? '提交中...' : '提交病历' }}
					</el-button>
					<el-button 
						@click="resetForm" 
						size="large"
						class="reset-btn"
					>
						<i class="el-icon-refresh"></i>
						重置表单
					</el-button>
				</div>
			</el-form>
		</el-card>
	</div>
</template>

<script>
import http from "@/utils/request";

export default {
	data() {
		return {
			itemList: [],
			patientList: [],
			visitId: '',
			selectedPatient: null,
			selectedItem: '',
			impression: '',
			performance: '',
			checkSite: '',
			selectedFile: null,
			ossUrl: '',
			submitting: false,
			resultData: {
				visitId: '',
				reportType: '',
				reportName: '',
				itemCode: '',
				resultItems: '',
				conclusion: '',
				reporterId: '',
				reportTime: '',
				verifyDoctorId: '',
				verifyTime: '',
				createdtime: '',
				ossUrl: ''
			}
		}
	},
	computed: {
		resultItemsJson() {
			const resultItems = {
				"印象": this.impression || '',
				"表现": this.performance || '',
				"检查方法": this.resultData.reportName || '',
				"检查部位": this.checkSite || ''
			};
			return JSON.stringify(resultItems, null, 2);
		}
	},
	async created() {
		await this.loadItemList();
	},
	methods: {
		async loadItemList() {
			try {
				const resp = await http.get("/doctor/getItemList");
				if (resp.data.code === 1) {
					this.itemList = resp.data.data || [];
				}
			} catch (error) {
				console.error('加载项目列表失败:', error);
			}
		},

		async getPatientByvisitId() {
			if (!this.visitId.trim()) {
				this.$message.warning('请输入诊疗号');
				return;
			}

			try {
				const resp = await http.get('/doctor/searchPatients', {
					params: {
						doctorId: this.$store.state.user.id,
						keyword: this.visitId
					}
				});

				if (resp.data.code === 1) {
					this.patientList = resp.data.data || [];
					if (this.patientList.length === 0) {
						this.$message.info('未找到相关患者');
					}
				} else {
					this.$message.error(resp.data.msg || '搜索失败');
				}
			} catch (error) {
				console.error('搜索患者失败:', error);
				this.$message.error('搜索失败');
			}
		},

		handleItemChange(itemCode) {
			const selected = this.itemList.find(item => item.itemCode === itemCode);
			if (selected) {
				this.resultData.itemCode = selected.itemCode;
				this.resultData.reportName = selected.itemName;
			}
		},
		
		handleFileChange(file, fileList) {
			const rawFile = file.raw;
			if (!rawFile) return;
			
			const validTypes = ['image/jpeg', 'image/png', 'image/gif', 'application/pdf'];
			if (!validTypes.includes(rawFile.type)) {
				this.$message.error('只支持JPG、PNG、GIF图片和PDF格式');
				return false;
			}
			
			if (rawFile.size > 50 * 1024 * 1024) {
				this.$message.error('文件大小不能超过50MB');
				return false;
			}
			
			this.selectedFile = rawFile;
		},
		
		removeFile() {
			this.selectedFile = null;
			return true;
		},
		
		async uploadFileToOSS(file) {
			try {
				const formData = new FormData();
				formData.append('file', file);
				
				const resp = await http.post('/doctor/newOssFile', formData, {
					headers: {
						'Content-Type': 'multipart/form-data'
					}
				});
				
				if (resp.data.code === 1) {
					return resp.data.data;
				} else {
					throw new Error(resp.data.msg || '上传失败');
				}
			} catch (error) {
				console.error('文件上传失败:', error);
				throw error;
			}
		},
		
		buildResultItems() {
			const resultItems = {
				"印象": this.impression || '',
				"表现": this.performance || '',
				"检查方法": this.resultData.reportName || '',
				"检查部位": this.checkSite || ''
			};
			return JSON.stringify(resultItems);
		},

		async submitForm() {
			try {
				this.submitting = true;
				
				this.resultData.visitId = this.selectedPatient.visitId;
				this.resultData.reporterId = this.$store.state.user.id;
				this.resultData.verifyDoctorId = this.$store.state.user.id;
				this.resultData.reportTime = new Date().toISOString().slice(0, 19).replace('T', ' ');
				this.resultData.verifyTime = new Date().toISOString().slice(0, 19).replace('T', ' ');
				this.resultData.createdtime = new Date().toISOString().slice(0, 19).replace('T', ' ');
				
				this.resultData.resultItems = this.buildResultItems();
				
				if (!this.resultData.reportType || !this.resultData.reportName || !this.resultData.itemCode || !this.resultData.conclusion) {
					this.$message.warning('请填写所有必填字段');
					this.submitting = false;
					return;
				}
				
				if (this.selectedFile) {
					try {
						this.$message.info('正在上传文件...');
						const ossUrl = await this.uploadFileToOSS(this.selectedFile);
						this.resultData.ossUrl = ossUrl;
						this.$message.success('文件上传成功');
					} catch (error) {
						this.$message.error('文件上传失败: ' + error.message);
						this.submitting = false;
						return;
					}
				} else {
					this.resultData.ossUrl = '';
				}
				
				console.log('提交的数据:', this.resultData);

				const resp = await http.post('/doctor/newMedicalReport', this.resultData);

				if (resp.data.code === 1) {
					this.$message.success('病历创建成功');
					this.resetForm();
				} else {
					this.$message.error(resp.data.msg || '创建失败');
				}
			} catch (error) {
				console.error('提交病历失败:', error);
				this.$message.error('提交失败: ' + error.message);
			} finally {
				this.submitting = false;
			}
		},

		resetForm() {
			this.resultData = {
				visitId: '',
				reportType: '',
				reportName: '',
				itemCode: '',
				resultItems: '',
				conclusion: '',
				reporterId: '',
				reportTime: '',
				verifyDoctorId: '',
				verifyTime: '',
				createdtime: '',
				ossUrl: ''
			};
			this.impression = '';
			this.performance = '';
			this.checkSite = '';
			this.selectedItem = '';
			this.selectedPatient = null;
			this.patientList = [];
			this.visitId = '';
			this.selectedFile = null;
			this.ossUrl = '';
		},

		// 辅助方法
		stringToColor(str) {
			let hash = 0;
			for (let i = 0; i < str.length; i++) {
				hash = str.charCodeAt(i) + ((hash << 5) - hash);
			}
			const color = `hsl(${hash % 360}, 70%, 60%)`;
			return color;
		},

		getInitials(name) {
			return name ? name.charAt(0).toUpperCase() : 'U';
		},

		getFileIconColor(file) {
			if (file.type.includes('image')) return '#67C23A';
			if (file.type === 'application/pdf') return '#F56C6C';
			return '#909399';
		},

		formatFileSize(bytes) {
			if (bytes === 0) return '0 Bytes';
			const k = 1024;
			const sizes = ['Bytes', 'KB', 'MB', 'GB'];
			const i = Math.floor(Math.log(bytes) / Math.log(k));
			return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
		}
	}
}
</script>

<style scoped>
.medical-report-container {
	max-width: 1200px;
	margin: 0 auto;
	padding: 20px;
}

/* 卡片样式 */
.search-card,
.patient-card,
.form-card {
	margin-bottom: 24px;
	border: 1px solid #e4e7ed;
	border-radius: 12px;
	background: #fff;
	transition: all 0.3s ease;
}

.search-card:hover,
.patient-card:hover,
.form-card:hover {
	box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 12px 0;
	border-bottom: 1px solid #f0f0f0;
	margin-bottom: 20px;
}

.header-left {
	display: flex;
	align-items: center;
	gap: 10px;
}

.form-icon {
	font-size: 24px;
	color: #409EFF;
}

.header-title {
	font-size: 18px;
	font-weight: 600;
	color: #303133;
}

.patient-count {
	font-size: 14px;
	color: #909399;
}

/* 搜索区域 */
.search-input {
	width: 100%;
}

.search-btn {
	width: 100%;
	background: linear-gradient(135deg, #409EFF, #66b1ff);
	border: none;
}

.search-btn:hover {
	background: linear-gradient(135deg, #66b1ff, #409EFF);
	transform: translateY(-1px);
}

/* 患者列表 */
.patient-list {
	display: flex;
	flex-direction: column;
	gap: 12px;
	width: 100%;
}

.patient-item {
	cursor: pointer;
	transition: all 0.3s ease;
	border: 2px solid transparent;
	border-radius: 8px;
	overflow: hidden;
}

.patient-item:hover {
	transform: translateY(-2px);
	box-shadow: 0 4px 12px rgba(64, 158, 255, 0.1);
}

.patient-item.selected {
	border-color: #409EFF;
	background: linear-gradient(135deg, #f0f9ff, #e6f7ff);
}

.patient-radio {
	width: 100%;
	padding: 0;
}

.patient-radio >>> .el-radio__input {
	display: none;
}

.patient-info {
	display: flex;
	align-items: center;
	gap: 16px;
	padding: 16px;
}

.patient-avatar {
	flex-shrink: 0;
	color: white;
	font-weight: bold;
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.patient-details {
	flex: 1;
}

.patient-name {
	font-size: 16px;
	font-weight: 500;
	color: #303133;
	margin-bottom: 8px;
}

.patient-id {
	display: flex;
	align-items: center;
	gap: 4px;
}

.patient-id >>> .el-tag {
	background: #f5f7fa;
	border: 1px dashed #dcdfe6;
}

/* 表单样式 */
.medical-form {
	padding: 8px;
}

.full-width {
	width: 100%;
}

/* 选项样式 */
.option-item {
	display: flex;
	align-items: center;
	gap: 10px;
	padding: 8px;
}

.type-icon {
	font-size: 18px;
}

.type-icon.test {
	color: #67C23A;
}

.type-icon.image {
	color: #409EFF;
}

.type-icon.pathology {
	color: #E6A23C;
}

.item-name {
	flex: 1;
	font-weight: 500;
}

.item-code {
	font-size: 12px;
	color: #909399;
	background: #f5f7fa;
	padding: 2px 8px;
	border-radius: 10px;
	border: 1px solid #e4e7ed;
}

.item-code-display {
	margin-top: 8px;
}

.item-code-display >>> .el-tag {
	background: #f0f9ff;
	border-color: #b3d8ff;
	color: #409EFF;
}

/* 文件上传 */
.file-upload {
	width: 100%;
}

.file-upload >>> .el-upload-dragger {
	border: 2px dashed #dcdfe6;
	border-radius: 8px;
	padding: 40px 20px;
	background: #fafafa;
	transition: all 0.3s ease;
}

.file-upload >>> .el-upload-dragger:hover {
	border-color: #409EFF;
	background: #f0f9ff;
}

.file-upload >>> .el-icon-upload {
	font-size: 48px;
	color: #c0c4cc;
	margin-bottom: 16px;
}

.file-upload >>> .el-upload__text {
	color: #606266;
	font-size: 14px;
}

.file-upload >>> .el-upload__text em {
	color: #409EFF;
	font-style: normal;
}

.file-upload >>> .el-upload__tip {
	color: #909399;
	font-size: 12px;
	margin-top: 8px;
}

.file-preview {
	margin-top: 16px;
}

.file-card {
	border: 1px dashed #dcdfe6;
	border-radius: 8px;
	background: #fafafa;
}

.file-info {
	display: flex;
	align-items: center;
	gap: 12px;
	padding: 12px;
}

.file-icon {
	font-size: 32px;
}

.file-details {
	flex: 1;
}

.file-name {
	font-weight: 500;
	color: #303133;
	margin-bottom: 4px;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}

.file-size {
	font-size: 12px;
	color: #909399;
}

.remove-btn {
	margin-left: auto;
	background: #fef0f0;
	border-color: #fde2e2;
	color: #f56c6c;
}

.remove-btn:hover {
	background: #f56c6c;
	border-color: #f56c6c;
	color: white;
}

/* 结构化结果 */
.structured-result-section {
	margin-top: 32px;
	padding-top: 24px;
	border-top: 1px solid #e4e7ed;
}

.section-header {
	display: flex;
	align-items: center;
	gap: 8px;
	margin-bottom: 24px;
	font-size: 16px;
	font-weight: 600;
	color: #303133;
}

.section-header i {
	color: #409EFF;
	font-size: 20px;
}

.result-fields {
	margin-bottom: 24px;
}

.result-fields >>> .el-form-item__label {
	font-weight: 500;
}

.result-fields >>> .el-textarea__inner {
	border: 1px solid #e4e7ed;
	border-radius: 6px;
	transition: all 0.3s;
}

.result-fields >>> .el-textarea__inner:focus {
	border-color: #409EFF;
	box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
}

/* JSON预览 */
.json-preview-card {
	background: #fafafa;
	border: 1px solid #e4e7ed;
	border-radius: 8px;
}

.preview-header {
	display: flex;
	align-items: center;
	gap: 8px;
	font-size: 14px;
	font-weight: 500;
	color: #303133;
}

.preview-header i:first-child {
	color: #409EFF;
}

.preview-header i:last-child {
	color: #909399;
	cursor: pointer;
}

.json-preview {
	margin: 0;
	padding: 16px;
	background: #f8f9fa;
	border-radius: 6px;
	font-family: 'Consolas', 'Monaco', monospace;
	font-size: 13px;
	line-height: 1.5;
	color: #333;
	max-height: 200px;
	overflow: auto;
	border: 1px solid #e4e7ed;
}

.json-preview::-webkit-scrollbar {
	width: 6px;
}

.json-preview::-webkit-scrollbar-track {
	background: #f1f1f1;
	border-radius: 3px;
}

.json-preview::-webkit-scrollbar-thumb {
	background: #c1c1c1;
	border-radius: 3px;
}

.json-preview::-webkit-scrollbar-thumb:hover {
	background: #a8a8a8;
}

/* 操作按钮 */
.form-actions {
	display: flex;
	justify-content: center;
	gap: 20px;
	margin-top: 40px;
	padding-top: 24px;
	border-top: 1px solid #e4e7ed;
}

.submit-btn {
	min-width: 140px;
	background: linear-gradient(135deg, #67c23a, #85ce61);
	border: none;
	box-shadow: 0 2px 6px rgba(103, 194, 58, 0.3);
}

.submit-btn:hover {
	background: linear-gradient(135deg, #85ce61, #67c23a);
	transform: translateY(-2px);
	box-shadow: 0 4px 12px rgba(103, 194, 58, 0.4);
}

.reset-btn {
	min-width: 120px;
	background: #f5f7fa;
	border-color: #dcdfe6;
	color: #606266;
}

.reset-btn:hover {
	background: #e4e7ed;
	border-color: #c0c4cc;
	color: #303133;
	transform: translateY(-1px);
}

/* 响应式设计 */
@media (max-width: 768px) {
	.medical-report-container {
		padding: 12px;
	}
	
	.el-col {
		width: 100%;
		margin-bottom: 20px;
	}
	
	.form-actions {
		flex-direction: column;
		gap: 12px;
	}
	
	.submit-btn,
	.reset-btn {
		width: 100%;
	}
	
	.result-fields .el-col {
		width: 100%;
		margin-bottom: 20px;
	}
}
</style>